package posts

import (
	"gitee.com/jjj-server/mdb"
	"log"
	"strconv"
	"time"
)

type Job struct {
	Title string `json:"title"`
	Publisher string `json:"publisher"`
	Jid string `json:"jid"`
	Content string `json:"content"`
	Date string `json:"date"`
}

// 获取兼职数量
func GetJobCount()int{
	db := mdb.ConnectDB()
	defer db.Close()
	count := 0
	rows,err := db.Query("SELECT * FROM job")
	if err != nil{
		log.Println("<< Failed to get job count: ",err)
	}
	for rows.Next(){
		count ++
	}
	return count
}



// 生成兼职ID
func GenerateJobID()string{
	id := "job"
	count := GetJobCount()
	count_str := strconv.Itoa(count+1)
	return id+count_str
}


func AddJob(title string,pubId string,content string)bool{
	date := time.Now().Format("2006-01-02 15:04:05")
	jid := GenerateJobID()

	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("INSERT INTO job(title, publisher, jid, content, date)",title,pubId,jid,content,date)
	if err != nil{
		log.Println("<< Failed to add job content: ",err)
		return false
	}
	return true
}

func DelJob(jid string)bool{
	db := mdb.ConnectDB()
	defer db.Close()
	_,err := db.Exec("DELETE FROM job WHERE jid = ?",jid)
	if err != nil{
		log.Println("<< Failed to add job content: ",err)
		return false
	}
	return true
}

// 获取指定ID兼职信息
func GetJobById(jid string)Job{
	db := mdb.ConnectDB()
	defer db.Close()
	row := db.QueryRow("SELECT title,publisher,content,date FROM job WHERE jid = ?",jid)
	job := Job{}
	row.Scan(&job.Title,&job.Publisher,&job.Content,&job.Date)
	job.Jid = jid
	return job
}

// 获取最近兼职信息
func GetJobRecentFive()[]Job{
	db := mdb.ConnectDB()
	defer db.Close()
	count := GetJobCount()
	jobs := []Job{}
	for i:=0;i<5;i++{
		job := GetJobById(strconv.Itoa(count))
		jobs = append(jobs,job)
		count -= 1
	}
	return jobs
}

// 获取兼职信息范围
/*
func GetJobSildeFive(slideTime int)[]Job{
	db := mdb.ConnectDB()
	defer db.Close()
	count := GetJobCount()
	jobs := []Job{}

	for i:=0;i<5;i++{
		jid := strconv.Itoa(count-slideTime*5)
		job := GetJobById(jid)
		jobs = append(jobs,job)
	}
	return jobs
}
*/
